<?php
/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/4/8
 * Time: 15:11
 */

namespace Webview\Controller;

use Admin\Api\SecurityCodeApi;
use Admin\Model\SecurityCodeModel;
use Common\Api\AccountApi;
use Common\Api\BoyeServiceApi;
use Shop\Api\MemberConfigApi;
use Shop\Api\RedEnvelopeApi;
use Think\Controller;
use Ucenter\Api\MemberApi;
use Uclient\Api\UserApi;
use Uclient\Model\OAuth2TypeModel;
use Uclient\Model\UcenterMemberModel;
use Common\Util\EnvCheck;

class UserController extends Controller{

    public function register(){
        if(IS_GET){
            $invite_id = I('invite_id','');
            if($invite_id === ''){
                $this -> error('操作错误');
            }
            $this -> assign('invite_id',$invite_id);
            $this -> display();
        }else{
            $username = I('post.username','');
            $code = I('post.code','');
            $password = I('post.password','');
            if($username == '' || $code == '' || $password == ''){
                $this -> error('参数缺失');
            }
            $invite_id = I('post.invite_id',0);
            $type = 3;
            $from = 0;
            $email = '';
            $sex = 0;
            $error = $this->isLegal($type,$username,$from);

            $map = array(
                'idcode' => $invite_id,
            );

            $result = apiCall(MemberConfigApi::GET_INFO,array($map));

            if($result['status']){
                $invite_id = $result['info']['uid'];
            }else{
                $this -> error($result['info']);
            }

            if (!($error === false)) {
                $this->error($error);
            }

            $mobile = "";
            $idcode = "";

            if($type == UcenterMemberModel::ACCOUNT_TYPE_MOBILE){
                if($code){

                }
                $mobile = $username;
                $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$mobile,SecurityCodeModel::TYPE_FOR_REGISTER));
                if(!$result['status']){
                    $this -> error($result['info']);
                }
                $username = 'M'.$mobile;

                $idcode = getIDCode($mobile,'M');
            }

            $nickname = I("nickname", "初来乍到");

            $entity = array(
                'username' => $username,
                'password' => $password,
                'from' => $from,
                'mobile' => $mobile,
                'realname' => '',
                'nickname' => $nickname ,
                'email' => $email,
                'idnumber' => '',
                'birthday' => time(),
                'idcode'=>$idcode,
                'type'=>$type,
                'invite_id'=>$invite_id,
                'sex'=>$sex,
            );

            $result = apiCall(AccountApi::REGISTER,array($entity));
            if ($result['status']) {

                $uid = $result['info'];

                $result = apiCall(RedEnvelopeApi::REG_ADD,array($uid));

                $flag = 0;

                if(!$result['status']){
                    $flag = 1;
                }

                $result = apiCall(MemberApi::RAISE_SCORE,array($uid,50));

                if(!$result['status']){
                    $flag = 1;
                }

                if($invite_id != "" && is_numeric($invite_id)){
                    $result = apiCall(MemberApi::RAISE_SCORE,array($invite_id,100));
                }

                if($flag == 1){
                    $this -> success("注册成功!红包或者积分发放出现错误,请联系管理员!");
                }else{
                    $this ->success("注册成功!",U('Webview/User/download'));
                }


            } else {
                $this->error($result['info']);
            }

        }

    }

    public function download(){

        $check = new EnvCheck();
        //Android 链接
        $android_url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.itboye.banma&g_f=991653";
        $ios_url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.itboye.banma&g_f=991653";

        $this->assign("url",$android_url);
        $this->assign("is_weixin",0);
        $this->assign("is_iphone",0);

        if($check->isWeixinBrowse()){
            $this->assign("is_weixin",1);
        }

        if($check->isIphone()){
            //IOS 链接
            $this->assign("url",$ios_url);
            $this->assign("is_iphone",1);
        }

        $this -> display();
    }

    public function getCode(){
        $mobile = I('post.username','');
        $tpye = SecurityCodeModel::TYPE_FOR_REGISTER;

        $data = array(
            'mobile'=>$mobile,
            'code_type'=>$tpye,
            'api_ver'=>100,
            'notify_id'=>111,
            'type'=>'BY_Message_send_sms',
            'alg'=>'md5',
        );

        $service = new BoyeServiceApi();

        $result= $service->callRemote("",$data,false);
        if($result['status']){
            $info = $result['info'];
            if($info['status']){
                $this->success($info);
            }else{
                $this->error($info);
            }
        }else{
            $this->error($result['info']);
        }
    }

    /**
     * 检查这些参数是否合法
     * @param $type
     * @param $username
     * @param $from
     * @return bool|string
     */
    private function isLegal($type,$username,$from){

        //TODO: 检查from的值是否合法
        //TODO: 检测用户账号是否合法
        //1. $type = 1 的时候 $username 是用户名
        //2. $type = 2 的时候 $username 是邮箱,应该符合邮箱规则
        //3. $type = 4 的时候 $username 是手机,应该符合手机的规则
        $from = intval($from);
        if(!OAuth2TypeModel::checkType($from)){
            return "用户来源参数无效";
        }

        if($type == UcenterMemberModel::ACCOUNT_TYPE_MOBILE && $this->getUsernameType($username) != $type){
            //$this->apiReturnErr($type." ".$this->getUsernameType($username))    ;
            $this->error("手机号非法!");
        }

        $notes=  "检测用户名:".$username."来源";

        $result =  apiCall(UserApi::CHECK_USER_NAME,array($username));
        if(!$result['status']){
            return "用户名已被注册!";
        }

        $result = apiCall(UserApi::CHECK_MOBILE,array($username));
        if(!$result['status']){
            return "手机号已被注册";
        }


        addLog("isLegal",$result,"",$notes);

        return false;

    }

    /**
     * 检测登录账户的类型
     * 3: 手机号
     * 2:  EMAIL
     * @param $str
     * @return int
     */
    private function getUsernameType($str){

        //return $str." ".preg_match("/^1\d{10}$/",$str);

        if(preg_match("/^1\d{10}$/",$str)){
            return UcenterMemberModel::ACCOUNT_TYPE_MOBILE;
        }

        return UcenterMemberModel::ACCOUNT_TYPE_USERNAME;
    }

}